package com.lf.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lf.entity.view.ViewUserResourceList;
import com.lf.enums.ErrorCodeEnum;
import com.lf.jwt.SameUrlData;
import com.lf.mapper.ViewUserResourceListMapper;
import com.lf.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//import com.tuohang.hydra.framework.common.spring.SpringKit;
//import com.tuohang.hydra.toolkit.basis.string.StringKit;

/**
 * @Title: url权限拦截器
 * @Description: 将用户访问的url和参数结合token存入redis，每次访问进行验证是否重复请求接口
 * @Auther: xhq
 * @Version: 1.0
 * @create 2019/3/26 10:35
 */
@Slf4j
@Component
public class UrlPermissionInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ViewUserResourceListMapper viewUserResourceListMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            JSON jsonObject = this.getJSONObject(request);
            Map<String, String> parameterMap = JSON.parseObject(jsonObject.toJSONString(), Map.class);

            ViewUserResourceList viewUserResourceList = new ViewUserResourceList();
            viewUserResourceList.setId(Long.valueOf(parameterMap.get("id")));
            viewUserResourceList.setUrl(request.getServletPath());
            int count = viewUserResourceListMapper.selectCount(viewUserResourceList);

//            log.warn("request url:"+ request.getServletPath());
            if(count <= 0){
                JSONObject result = new JSONObject();
                result.put("code", ErrorCodeEnum.PARAM_200030.code());
                result.put("message",ErrorCodeEnum.PARAM_200030.msg());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(result.toString());
                response.getWriter().close();
//                    拦截之后跳转页面
//                    String formRequest = request.getRequestURI();
//                    request.setAttribute("myurl", formRequest);
//                    request.getRequestDispatcher("/WebRoot/common/error/jsp/error_message.jsp").forward(request, response);
                return false;
            }else {//如果不是重复相同数据
                return true;
            }
        } else {
            return super.preHandle(request, response, handler);
        }
    }


    private JSON getJSONObject(HttpServletRequest req) {
        String str = null, retStr = "";
        try {
            BufferedReader br = req.getReader();
            while ((str = br.readLine()) != null) {
                retStr += str;
            }
            if (StringUtils.isNotBlank(retStr)) {
                JSONObject jsonObject = JSONObject.parseObject(retStr);
                if (null == jsonObject) {
                    JSONArray.parseArray(retStr);
                }
                return jsonObject;
            }
        } catch (Exception e) {
            try {
                return JSONArray.parseArray(retStr);
            } catch (Exception ex) {
                return null;
            }
        }
        return null;
    }
}